import IntroPage from '../pageobjects/intro.page'
import NativePickerPage from '../pageobjects/nativePickerPage'
import {
  pushSampleFiles,
  sampleFileNames,
  sampleFileNamesExceptExtensions,
} from '../fileFactory/sampleFileFactory'
import OpenPage from '../pageobjects/open.page'
import { androidResolverActivity, appActivity, reloadApp } from '../utils'
import { DocumentPickerResponse } from '@react-native-documents/picker/src'

describe('documents-open-tests', () => {
  beforeAll(async () => {
    await pushSampleFiles()
  })

  beforeEach(async () => {
    await reloadApp()
    await IntroPage.gotoOpenExample()
  })

  it('can open a pdf file, even after app restart', async () => {
    await OpenPage.openPdfFile()

    await NativePickerPage.ensureUserIsInDownloads()
    for (const name of sampleFileNamesExceptExtensions(['.pdf'])) {
      expect(await NativePickerPage.getFileItemEnabled(name)).toBe(false)
    }
    await NativePickerPage.selectSamplePdf()
    const pdfValues = await OpenPage.getResultById(0)

    const expectedPdf: Partial<DocumentPickerResponse> = {
      error: null,
      isVirtual: false,
      name: sampleFileNames.pdf,
      convertibleToMimeTypes: null,
      size: 13264,
      type: 'application/pdf',
      hasRequestedType: true,
      uri: jasmine.stringContaining('content://') as any,
    }

    expect(pdfValues).toEqual(jasmine.objectContaining(expectedPdf))
    async function assertCanPreviewOpenedPdf() {
      await OpenPage.viewLastDocument()
      const previewActivity = await driver.getCurrentActivity()
      expect(previewActivity).not.toBe(appActivity)
      expect(previewActivity).not.toBe(androidResolverActivity)
      await driver.back()
    }
    await assertCanPreviewOpenedPdf()
    await reloadApp()

    await IntroPage.gotoOpenExample()
    await assertCanPreviewOpenedPdf()
  })
})
